package org.sidora.strata.context;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Dating;
import org.sidora.core.Phase;
import org.sidora.core.context.Context;
import org.sidora.core.util.AbstractInventory;
import org.sidora.strata.Storage;
import org.w3c.dom.events.MouseEvent;


/**
 * ChronoPropertiesTopComponent which displays something
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class ChronoPropertiesTopComponent extends TopComponent {
    
    private static ChronoPropertiesTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "ChronoPropertiesTopComponent";
    
    private ChronoPropertiesTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(ChronoPropertiesTopComponent.class, "CTL_ChronoPropertiesTopComponent"));
        setToolTipText(NbBundle.getMessage(ChronoPropertiesTopComponent.class, "HINT_ChronoPropertiesTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldTPQStandard = new javax.swing.JTextField();
        jTextFieldTAQStandard = new javax.swing.JTextField();
        jTextFieldTPQMade = new javax.swing.JTextField();
        jTextFieldTAQMade = new javax.swing.JTextField();
        jTextFieldTPQMaterials = new javax.swing.JTextField();
        jTextFieldTAQMaterials = new javax.swing.JTextField();
        jTextFieldPhase = new javax.swing.JTextField();

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Standard");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Made");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Materials");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Phase");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, "TPQ");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, "TAQ");

        jTextFieldTPQStandard.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTPQStandardFocusLost(evt);
            }
        });

        jTextFieldTAQStandard.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTAQStandardFocusLost(evt);
            }
        });

        jTextFieldTPQMade.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTPQMadeFocusLost(evt);
            }
        });

        jTextFieldTAQMade.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTAQMadeFocusLost(evt);
            }
        });

        jTextFieldTPQMaterials.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTPQMaterialsFocusLost(evt);
            }
        });

        jTextFieldTAQMaterials.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTAQMaterialsFocusLost(evt);
            }
        });

        jTextFieldPhase.setEditable(false);
        jTextFieldPhase.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldPhaseMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 92, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jLabel5)
                        .add(59, 59, 59)
                        .add(jLabel6)
                        .add(20, 20, 20))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel4)
                            .add(jLabel2)
                            .add(jLabel1)
                            .add(jLabel3))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jTextFieldTPQStandard, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jTextFieldTPQMade, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jTextFieldTPQMaterials, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(15, 15, 15)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jTextFieldTAQMaterials, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jTextFieldTAQMade, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(jTextFieldTAQStandard, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                            .add(jTextFieldPhase))))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(new java.awt.Component[] {jTextFieldTAQMade, jTextFieldTAQMaterials, jTextFieldTAQStandard, jTextFieldTPQMade, jTextFieldTPQMaterials, jTextFieldTPQStandard}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(jLabel5))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldTPQStandard, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextFieldTAQStandard, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldTPQMade, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextFieldTAQMade, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldTPQMaterials, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextFieldTAQMaterials, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldPhase, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void jTextFieldPhaseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldPhaseMouseClicked
        addPhaseMenu();
        jPopupMenu.show(jTextFieldPhase,evt.getX(),evt.getY());
    }//GEN-LAST:event_jTextFieldPhaseMouseClicked
    
    private void jTextFieldTAQMaterialsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTAQMaterialsFocusLost
        saveFields();
    }//GEN-LAST:event_jTextFieldTAQMaterialsFocusLost
    
    private void jTextFieldTPQMaterialsFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTPQMaterialsFocusLost
        saveFields();
    }//GEN-LAST:event_jTextFieldTPQMaterialsFocusLost
    
    private void jTextFieldTAQMadeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTAQMadeFocusLost
        saveFields();
    }//GEN-LAST:event_jTextFieldTAQMadeFocusLost
    
    private void jTextFieldTPQMadeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTPQMadeFocusLost
        saveFields();
    }//GEN-LAST:event_jTextFieldTPQMadeFocusLost
    
    private void jTextFieldTAQStandardFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTAQStandardFocusLost
        saveFields();
    }//GEN-LAST:event_jTextFieldTAQStandardFocusLost
    
    private void jTextFieldTPQStandardFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTPQStandardFocusLost
        saveFields();
    }//GEN-LAST:event_jTextFieldTPQStandardFocusLost
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextFieldPhase;
    private javax.swing.JTextField jTextFieldTAQMade;
    private javax.swing.JTextField jTextFieldTAQMaterials;
    private javax.swing.JTextField jTextFieldTAQStandard;
    private javax.swing.JTextField jTextFieldTPQMade;
    private javax.swing.JTextField jTextFieldTPQMaterials;
    private javax.swing.JTextField jTextFieldTPQStandard;
    // End of variables declaration//GEN-END:variables
    private JPopupMenu jPopupMenu;
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized ChronoPropertiesTopComponent getDefault() {
        if (instance == null) {
            instance = new ChronoPropertiesTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the ChronoPropertiesTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ChronoPropertiesTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find ChronoProperties component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ChronoPropertiesTopComponent) {
            return (ChronoPropertiesTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        // TODO add custom code on component opening
    }
    
    public void componentClosed() {
        // TODO add custom code on component closing
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return ChronoPropertiesTopComponent.getDefault();
        }
    }
    
    public void fillFields(){
        Dating dating = Storage.getContext().getDating();
        
        if (dating != null){
            jTextFieldTPQStandard.setText(dating.getTpq().toString());
            jTextFieldTAQStandard.setText(dating.getTaq().toString());
            jTextFieldTPQMaterials.setText(dating.getTpqmaterial().toString());
            jTextFieldTAQMaterials.setText(dating.getTaqmaterial().toString());
            jTextFieldTPQMade.setText(dating.getTpqformation().toString());
            jTextFieldTAQMade.setText(dating.getTaqformation().toString());
            fillPhases();
            //TODO Phase
        } else {
            emptyFields();
        }
    }
    
    public void emptyFields(){
        jTextFieldTPQStandard.setText("");
        jTextFieldTAQStandard.setText("");
        jTextFieldTPQMaterials.setText("");
        jTextFieldTAQMaterials.setText("");
        jTextFieldTPQMade.setText("");
        jTextFieldTAQMade.setText("");
        jTextFieldPhase.setText("");
    }
    
    public void saveFields(){
        Context context = Storage.getContext();
        Dating dating = new Dating();
        try{
            dating.setTpq(Integer.parseInt(jTextFieldTPQStandard.getText()));
        } catch (Exception e) {}
        try{
            dating.setTaq(Integer.parseInt(jTextFieldTAQStandard.getText()));
        } catch (Exception e) {}
        try{
            dating.setTpqformation(Integer.parseInt(jTextFieldTPQMade.getText()));
        } catch (Exception e) {}
        try{
            dating.setTaqformation(Integer.parseInt(jTextFieldTAQMade.getText()));
        } catch (Exception e) {}
        try{
            dating.setTpqmaterial(Integer.parseInt(jTextFieldTPQMaterials.getText()));
        } catch (Exception e) {}
        try{
            dating.setTaqmaterial(Integer.parseInt(jTextFieldTAQMaterials.getText()));
        } catch (Exception e) {}
        
        
        context.setDating(dating);
        AbstractInventory.setObject(context);
    }
    
    protected JPopupMenu addPhaseMenu() {
        jPopupMenu = new JPopupMenu();
        
        List<Phase> phases = Phase.Inventory.getList(Storage.getSite());
        
        Iterator <Phase>iter = phases.iterator();
        
        while (iter.hasNext()){
            final Phase phase = iter.next();
            final JMenuItem item = new JMenuItem();
            item.setText(phase.getName());
            jPopupMenu.add(item);
            item.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent arg0) {
                    Context context = Storage.getContext();
                    
                    if (context.getDating() == null)
                        context.setDating(new Dating());
                    
                    context.getDating().setPhase(phase);
                    AbstractInventory.setObject(context);
                    
                    jTextFieldPhase.setText(phase.getName());
                }
            });
        }
        return jPopupMenu;
    }
    
    
    private void fillPhases(){
        jTextFieldPhase.setText("");
        Context context = Storage.getContext();
        if (context == null)
            return;
        Dating dating = context.getDating();
        if (dating == null)
            return;
        Phase phase = dating.getPhase();
        if (phase == null)
            return ;
        jTextFieldPhase.setText(phase.toString());
        
    }
}
